<?php
namespace App\Services\AliCloud;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use App\Master\Framework\Extend\Module;
use Illuminate\Support\Facades\Cache;

class ALiService{
    // 日志模块名
    const LOG_MODULE = 'ALiService';

    // 微信公众号配置信息
    protected static $AccessKeyId;//微信id  #LTAI5tGrimHEvwf7yrZkFdf6
    protected static $AccessSecret;//应用id  #ZVGcFWjh0tq5UQIOqsj3ALrTKT93Wi
    protected static $SignName;//短信签名
    protected static $Template;//短信模板

    protected static $instance;
    public function __construct($config,$template)
    {
        self::$AccessKeyId  = $config['accessKeyId'];
        self::$AccessSecret = $config['accessSecret'];
        self::$SignName = $config['signName'];
        self::$Template = $template;
    }

    public static function getInstance($template = '')
    {
        if (!isset(self::$instance)) {
            $config = Cache::remember('ALiConfig',86400,function (){
                return Module::_SetupModule('ALiConfig');
            });
            self::$instance = new self($config,$template);
        }
        return self::$instance;
    }

    public function sendSms($mobile,$authData)
    {
        AlibabaCloud::accessKeyClient(self::$AccessKeyId, self::$AccessSecret)
            ->regionId('cn-hangzhou')
            ->asGlobalClient();
        try {
            $result = AlibabaCloud::rpc()
                ->product('Dysmsapi')
                ->version('2017-05-25')
                ->action('SendSms')
                ->method('POST')
                ->host('dysmsapi.aliyuncs.com')
                ->options([
                    'query' => [
                        'RegionId' => "cn-hangzhou",
                        'PhoneNumbers' => $mobile,
                        'SignName' => self::$SignName,
                        'TemplateCode' => self::$Template,
                        'TemplateParam' => json_encode($authData,JSON_UNESCAPED_UNICODE),
                    ],
                ])
                ->request();
            // 成功发送后的结果集
            //print_r($result->toArray());
            // 短信发送成功可以这里进行相关业务逻辑处理
            if ($result['Code'] != 'OK') return $result;
            return true;
        } catch (ClientException $e) {
            return $e->getErrorMessage() . PHP_EOL;
        } catch (ServerException $e) {
            return $e->getErrorMessage() . PHP_EOL;
        }
    }

    
}